import React from 'react';

import './tabs.scss';

export class Tabs extends React.Component {

    state = {tab: this.props.init};

    tabMap = new Map();

    componentWillMount(){
        var {children} = this.props, len = children.length;
        _.map(children, ({key}, i) => {
            this.tabMap.set(key, `${i}-${len}`);
        });
    }

    changeTab(tab){
        if(this.state.tab !== tab){
            this.setState({tab});
            _.invoke(this.props, 'onChange', tab);
        }
    }

    render(){
        var {children} = this.props, {tab} = this.state;
        return (
            <div className="tab">
                <div className="t-h flex-avg">
                    {_.map(children, m =>
                        <div
                            key={m.key}
                            onClick={() => this.changeTab(m.key)}
                            className={`th-item flex-avg${m.key === tab ? ' active' : ''}`}
                        >
                            {m.props.title}
                        </div>
                    )}
                    <div className={`th-link tl-${this.tabMap.get(tab)}`}/>
                </div>
                <div className="t-c">
                    {_.filter(children, m => m.key === tab)}
                </div>
            </div>
        );
    }

}

export const Tab = ({children}) => children;
